<template>
    <div class="login-page">
        <!-- ------------------ 医生&用户登录 ------------------ -->
        <el-form v-if="formType == 1" key="loginForm" :model="loginForm" :rules="loginFormRule" ref="loginForm" label-width="0px" class="login-container" @keydown.enter.native="onSubmitLogin">
            <h3 class="title">
                <div class="icon-arrow" @click="backHomePage"><i class="el-icon-arrow-left"></i></div> 欢迎登录
            </h3>
            <el-form-item prop="userType">
                <el-radio-group :key="formType" v-model="loginForm.userType">
                    <el-radio label="P">用户</el-radio>
                    <el-radio label="D">医生</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item prop="mobile">
                <el-input v-model="loginForm.mobile" placeholder="账号" maxlength="11" @blur="validAccount('loginForm')"></el-input>
                <!-- <input type="text" name="loginAccount" style="position:fixed; left: -9999px;" readonly> -->
            </el-form-item>
            <el-form-item prop="password">
                <!-- <input type="password" name="loginPwd" style="position:fixed; left: -9999px;" readonly> -->
                <el-input type="password" v-model="loginForm.password" maxlength="20" placeholder="密码" show-password></el-input>
            </el-form-item>
            <el-form-item prop="smsCode">
                <el-input class="sms-code" v-model="loginForm.smsCode" placeholder="验证码"></el-input>
                <el-button type="primary" plain :disabled="isGetting" @click="getPhoneCaptcha('loginForm')">
                    <span v-if="isGetting">{{ getTime }} 秒</span>
                    <span v-else>获取验证码</span>
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" plain style="width: 100%" @click="onSubmitLogin" :loading="loading">登 录</el-button>
            </el-form-item>
            <el-form-item>
                <el-checkbox v-model="serverChecked">我已阅读并同意</el-checkbox>
                <span class="open-server" @click="openServer">《{{serverItem.name}}》</span>
            </el-form-item>

            <div class="other-handle">
                <span class="handle-item" @click="gotoForget">忘记密码</span>
                <template v-if="loginForm.userType == 'P'">
                    <span>|</span>
                    <span class="handle-item" @click="gotoRegister">用户注册</span>
                </template>
            </div>
        </el-form>

        <!-- ------------------ 用户注册 ------------------ -->
        <el-form v-else-if="formType == 2" key="registerForm" :model="registerForm" :rules="registerFormRule" ref="registerForm" label-position="left" label-width="0px" class="login-container">
            <h3 class="title">
                <div class="icon-arrow" @click="gotoLogin"><i class="el-icon-arrow-left"></i></div> 用户注册
            </h3>
            <el-form-item prop="mobile" key="registerMobile">
                <el-input v-model="registerForm.mobile" placeholder="请输入手机号" maxlength="11" @blur="validAccount('registerForm')"></el-input>
                <!--  <input type="text" name="registerAccount" style="position:fixed; left: -9999px;" readonly> -->
            </el-form-item>
            <el-form-item prop="smsCode">
                <!-- <input type="password" name="registerSms" style="position:fixed; left: -9999px;" readonly> -->
                <el-input type="text" class="sms-code" v-model="registerForm.smsCode" placeholder="验证码"></el-input>
                <el-button type="primary" plain :disabled="isGetting" @click="getPhoneCaptcha('registerForm')">
                    <span v-if="isGetting">{{ getTime }} 秒</span>
                    <span v-else>获取验证码</span>
                </el-button>
            </el-form-item>
            <el-form-item prop="password">
                <el-input type="password" v-model="registerForm.password" placeholder="请输入密码" show-password @blur="toValidPwd('registerForm')"></el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword">
                <el-input type="password" v-model="registerForm.confirmPassword" placeholder="请再次输入密码" show-password></el-input>
            </el-form-item>
            <div class="mb">
                <el-button type="primary" plain style="width: 100%" @click="submitRegister('registerForm')" :loading="loading">立即注册</el-button>
            </div>
            <div class="mb">
                <el-checkbox v-model="serverChecked">我已阅读并同意</el-checkbox><span class="open-server" @click="openServer">《{{serverItem.name}}》</span>
            </div>
        </el-form>

        <!-- ------------------ 找回密码  ------------------ -->
        <el-form v-else-if="formType == 3" key="passwordForm" :model="passwordForm" :rules="passwordFormRule" ref="passwordForm" label-width="0px" class="login-container">
            <h3 class="title">
                <div class="icon-arrow" @click="gotoLogin"><i class="el-icon-arrow-left"></i></div> 找回密码
            </h3>
            <el-form-item prop="userType">
                <el-radio-group :key="formType" v-model="passwordForm.userType">
                    <el-radio label="P">用户</el-radio>
                    <el-radio label="D">医生</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item prop="mobile">
                <el-input v-model="passwordForm.mobile" placeholder="请输入手机号" maxlength="11" @blur="validAccount('passwordForm')"></el-input>
                <!--   <input type="text" name="registerAccount" style="position:fixed; left: -9999px;" readonly> -->
            </el-form-item>
            <el-form-item prop="smsCode">
                <!-- <input type="password" name="registerSms" style="position:fixed; left: -9999px;" readonly> -->
                <el-input type="text" class="sms-code" v-model="passwordForm.smsCode" placeholder="验证码"></el-input>
                <el-button type="primary" plain :disabled="isGetting" @click="getPhoneCaptcha('passwordForm')">
                    <span v-if="isGetting">{{ getTime }} 秒</span>
                    <span v-else>获取验证码</span>
                </el-button>
            </el-form-item>
            <el-form-item prop="password">
                <el-input type="password" v-model="passwordForm.password" placeholder="请输入密码" show-password @blur="toValidPwd('passwordForm')"></el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword" key="confirmPassword">
                <el-input type="password" v-model="passwordForm.confirmPassword" placeholder="请再次输入密码" show-password></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" plain style="width: 100%" @click="submitForgetPwd('passwordForm')" :loading="loading">找回密码</el-button>
            </el-form-item>
        </el-form>

        <!-- 选择角色 -->
        <el-dialog class="dialog-frame" width="600" :visible.sync="choiceUserDialog" @close="closeUserChoice()" :close-on-click-modal="false" :close-on-press-escape="false" title="登录身份">
            <el-select v-model="choiceUserType" placeholder="请选择登录身份" value-key="type">
                <el-option v-for="item in canChoiceOptions" :key="item.type" :label="$util.filterByIds(item.type, $dict.roleIds)" :value="item">
                </el-option>
            </el-select>
            <el-button type="primary" plain @click="checkDrAudit(choiceUserType)">确定</el-button>
        </el-dialog>

        <!-- 服务弹框 -->
        <el-dialog class="dialog-frame" width="600" :title="serverItem.name" :visible.sync="serverDialog">
            <div class="ql-snow ql-editor" v-html="serverItem.value"></div>
        </el-dialog>

        <!-- ------------------ 二维码弹框 ------------------ -->
        <qr-dialog ref="qrDialog"></qr-dialog>
    </div>
</template>

<script>
    import QrDialog from '@/components/go-mini-dialog';

    export default {
        name: 'Login',
        components: {
            QrDialog
        },
        data() {
            var validateNoPwd = (rule, value, callback, pwd) => {
                if (value != pwd) {
                    callback(new Error("两次输入的密码不一致，请重新输入"))
                } else {
                    callback()
                }
            }

            return {
                fullLoading: null,
                loading: false,
                formType: 1, // 1=login, 2=regiter, 3=forgetPwd
                loginType: 1,

                //登录窗口
                loginForm: {
                    userType: 'D',
                    documentNumber: '',
                    mobile: '18028573098',
                    password: '123456Yy_',
                    smsCode: '8888',
                },
                loginFormRule: {
                    userType: [{ required: true, message: '请选择角色', trigger: 'change' }],
                    mobile: [
                        { required: true, message: '请输入账号', trigger: 'blur' },
                        { validator: this.validateMobile, trigger: 'change' }
                    ],
                    smsCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' }
                    ],
                },
                //注册窗口
                registerForm: {
                    mobile: '',
                    smsCode: '',
                    password: '',
                    confirmPassword: '',
                },
                registerFormRule: {
                    mobile: [
                        { required: true, message: '请输入账号', trigger: 'blur' },
                        { validator: this.validateMobile, trigger: 'change' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { validator: this.$validate.validatePwdBySave, trigger: 'change' }
                    ],
                    confirmPassword: [
                        { required: true, message: '请再次输入密码', trigger: 'change' },
                        { validator: (r, v, cb) => validateNoPwd(r, v, cb, this.registerForm.password), trigger: 'change' }
                    ],
                    smsCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
                },
                //找回密码窗口
                passwordForm: {
                    userType: 'D',
                    mobile: '',
                    smsCode: '',
                    password: '',
                    confirmPassword: '',
                },
                passwordFormRule: {
                    mobile: [
                        { required: true, message: '请输入账号', trigger: 'blur' },
                        { validator: this.validateMobile, trigger: 'change' }
                    ],
                    smsCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { validator: this.$validate.validatePwdBySave, trigger: 'change' }
                    ],
                    confirmPassword: [
                        { required: true, message: '请再次输入密码', trigger: 'change' },
                        { validator: (r, v, cb) => validateNoPwd(r, v, cb, this.passwordForm.password), trigger: 'change' }
                    ],
                    userType: [{ required: true, message: '请选择角色', trigger: 'change' }],
                },

                isGetting: false,
                getTime: 60,
                countDown: null,

                captchaImg: '', // 图形验证码url
                captchaToken: '', // 图形验证码Token

                choiceUserDialog: false,
                choiceUserType: {}, //选择用户角色
                choiceOptions: [{
                    value: '1',
                    label: '用户'
                }, {
                    value: '2',
                    label: '服务端'
                }, {
                    value: '3',
                    label: '医生'
                }],
                canChoiceOptions: [],
                userType: [],

                serverChecked: true, //服务协议
                serverDialog: false, //服务协议弹框
                serverItem: {
                    name: '服务协议',
                    value: ''
                },
                serverHtml: '',

            }
        },
        beforeRouteLeave(to, from, next) {
            this.fullLoading && this.fullLoading.close();
            next()
        },
        methods: {
            //手机验证码
            getPhoneCaptcha(formName) {
                if (this.isGetting) return;

                this.isGetting = true;
                this.getTime = 60;

                this.countDown = null;
                this.countDown = setInterval(() => {
                    this.getTime--;
                    if (this.getTime <= 0) {
                        clearInterval(this.countDown);
                        this.isGetting = false;
                        this.countDown = null;
                    }
                }, 1000);

                let para = {
                    mobile: this[formName].mobile
                }

                if (this.formType == 2) {
                    // 用户注册
                    para.type = '3'
                    para.isRegister = 1;
                } else {
                    para.type = this[formName].userType == 'D' ? '3' : '1';
                    para.isRegister = 0;
                }

                this.$ajax.getPhoneCaptcha(para).then((res) => {
                    this.$util.message(res.msg, 'success');
                }).catch((err) => {
                    this.isGetting = false;
                    this.clearInterval()
                    this.$util.message(err.msg)
                })
            },
            //获取图形验证码
            getPicCaptcha() {
                this.$ajax.getPicCaptcha().then((res) => {
                    this.captchaImg = res.data.img || ''
                    this.captchaToken = res.data.cToken
                }).catch((err) => {
                    this.$util.message(err.msg);
                })
            },
            //失去焦点时判断用户类型
            validAccount(formName) {
                this.accountValid = false;
                if (this[formName].mobile && this[formName].mobile.length == 11) {
                    this.$ajax.judgeUser({
                        mobile: this[formName].mobile
                    }).then(res => {
                        this.userType = res.data.list || []

                        if (this.formType == 2 && this.userType.length > 0) {
                            this.$util.message('该账号已注册')
                        } else if ((this.formType == 1 || this.formType == 3) && this.userType.length < 1) {
                            this.$util.message('该账号尚未注册')
                        }
                    }).catch(err => {
                        this.$tuil.message(err.msg);
                    })
                }
            },
            getAgreement() {
                this.$ajax.getAgreementDetail({
                    id: 1
                }).then(res => {
                    this.serverItem.name = res.data.initName;
                    this.serverItem.value = res.data.initKey;
                }).catch(err => {
                    this.$util.message(err.msg);
                })
            },
            openServer() { //打开服务协议
                this.serverDialog = true;
            },
            gotoRegister() {
                this.formType = 2;
                this.resetForm('registerForm')
            },
            submitRegister(formName) { //用户注册
                if (!this.serverChecked) {
                    this.$util.message('请勾选服务协议');
                    return false;
                }

                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.loading = true;

                        let para = {
                            userType: 'P',
                            mobile: this.registerForm.mobile,
                            phoneCaptcha: this.registerForm.smsCode,
                            password: this.registerForm.password,
                            confirmPassword: this.registerForm.confirmPassword,
                        }

                        this.$ajax.userRegister(para).then((res) => {
                            this.loading = false;
                            this.$util.message(res.msg, 'success');
                            this.gotoLogin();
                        }).catch((err) => {
                            this.loading = false;
                            this.$util.message(err.msg)
                        })
                    }
                })
            },
            gotoForget() {
                this.formType = 3;
                this.resetForm('passwordForm')
            },
            submitForgetPwd(formName) { //找回密码
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.loading = true;

                        let para = {
                            userType: this.passwordForm.userType,
                            mobile: this.passwordForm.mobile,
                            phoneCaptcha: this.passwordForm.smsCode,
                            password: this.passwordForm.password,
                            confirmPassword: this.passwordForm.confirmPassword,
                        }

                        this.$ajax.retrievePassword(para).then((res) => {
                            this.loading = false;
                            this.$util.message(res.msg, 'success')
                            this.gotoLogin();
                        }).catch((err) => {
                            this.loading = false;
                            this.$util.message(err.msg)
                        })
                    }
                })
            },
            gotoLogin() {
                this.formType = 1;
                this.resetForm('loginForm')
            },
            // 提交登录
            onSubmitLogin() {
                if (!this.serverChecked) {
                    this.$util.message('请勾选服务协议');
                    return false;
                }

                this.$refs.loginForm.validate(valid => {
                    if (valid) {
                        this.loading = true;

                        let params = {
                            password: this.loginForm.password,
                            userType: this.loginForm.userType,
                        };

                        if (this.loginType == 2) { // 身份证登录
                            params.documentNumber = this.loginForm.documentNumber;
                        } else {
                            params.mobile = this.loginForm.mobile;
                            params.smsCode = this.loginForm.smsCode;
                        }

                        this.$ajax.userLogin(params).then(res => {
                            this.loading = false;

                            this.checkDrAudit(res.data.list[0]);
                        }).catch((err) => {
                            this.loading = false;

                            this.$util.message(err.msg)
                        })
                    }
                })
            },
            // 检测医生认证状态
            checkDrAudit(data = {}) {
                this.$setStore('accessToken', data.webToken)

                if (this.$global.isCa && this.loginType == 1 && data.type == 'D') {
                    this.fullLoading = this.$loading({
                        lock: true,
                        text: '登录中...',
                        spinner: 'el-icon-loading',
                        background: 'rgba(255, 255, 255, 0.3)'
                    })

                    this.$ajax.checkCaState({
                        mobile: this.loginForm.mobile
                    }).then(res => {
                        if (res.data.isCertification == 1) {
                            this.loginToHome(data);
                        } else {
                            this.$removeStore('accessToken')

                            if (this.choiceUserDialog) this.closeUserChoice()

                            this.$refs.qrDialog && this.$refs.qrDialog.onOpen()
                            this.fullLoading && this.fullLoading.close();
                        }
                    }).catch(err => {
                        this.fullLoading && this.fullLoading.close();
                        this.$util.message(err.msg);
                    })
                } else {
                    this.loginToHome(data);
                }
            },
            loginToHome(data) {
                if (!data.webToken) return false;

                this.$setStore('accessToken', data.webToken)
                this.$setStore('adminUserInfo', data)
                this.$util.initRouter(this)
                this.$router.push({ path: '/home' })
            },
            backHomePage() {
                this.$router.push({ path: '/home' })
            },
            resetForm(formName) {
                this.isGetting = false;
                this.getTime = 60;

                this.countDown && clearInterval(this.countDown);
                this.countDown = null;

                this.serverChecked = true;
                this[formName] = Object.assign({}, this.$options.data[formName])

                this.$nextTick(() => {
                    // this.$refs[formName] && this.$refs[formName].resetFields();
                    this.$refs[formName] && this.$refs[formName].clearValidate();
                })
            },
            closeUserChoice() {
                this.choiceUserDialog = false;
                this.choiceUserType = {};
                this.canChoiceOptions = []
            },
            validateMobile(rule, value, callback) {
                var reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;

                if (!value) {
                    callback('请输入账号')
                } else if (value.length <= 10 || !reg.test(value)) {
                    callback(new Error('请输入正确格式的手机号码'))
                } else {
                    callback()
                }
            },
            validateIdentify(rule, value, callback) {
                const reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;

                if (!value) {
                    callback('请输入身份证号')
                } else if (!reg.test(value)) {
                    callback(new Error("身份证号格式错误"))
                } else {
                    callback()
                }
            },
            clearInterval() {
                this.countDown && clearInterval(this.countDown);
                this.countDown = null;
            },
            toValidPwd(formName) {
                if (this[formName].confirmPassword) {
                    this.$refs[formName] && this.$refs[formName].validateField('confirmPassword')
                }
            }
        },
        mounted() {
            this.formType = 1;
            this.clearInterval();
            this.getAgreement();

            this.$ajax.getConfigureName().then(res => {
                this.$setStore('hospitalName', res.data.hospitalNamePc)
                this.$util.title(res.data.hospitalNamePc)
            })
        },
        beforeDestroy() {
            this.clearInterval();
        }
    }
</script>

<style lang="scss" scoped>
    .login-page {
        background: url("../../assets/img/login_bg.png") no-repeat top center;
        width: 100%;
        height: 100%;
        min-height: 100%;
        background-size: cover;
        overflow: auto;

        .dialog-frame {
            text-align: center;
        }

        .open-server:hover {
            color: #409eff;
            cursor: pointer;
        }

        .sms-code {
            width: 202px;
            margin-right: 18px;
        }

        .other-handle {
            color: $--type-info;
            text-align: center;

            .handle-item {
                margin: 0 12px;
                color: $--type-info;
                vertical-align: middle;
                cursor: pointer;

                &:hover {
                    color: $--type-primary;
                }
            }
        }

        .mb {
            margin-bottom: 22px;
        }
    }

    .login-container {
        background-clip: padding-box;
        margin: 180px auto;
        width: 400px;
        padding: 35px 30px 15px 30px;
        background: #fff;
        border: 1px solid #eaeaea;
        box-shadow: 0 0 25px #cac6c6;
        border-radius: 5px;

        .title {
            margin: 0px auto 27px auto;
            padding: 0 0 25px 0;
            text-align: center;
            color: #505458;
            border-bottom: 1px solid #eaeaea;
        }

        .icon-arrow {
            float: left;
            cursor: pointer;
        }

        .code-pic {
            width: 112px;
            height: 40px;
            // display: inline-block;
            float: right;

            img {
                width: 100%;
                height: 100%;
            }
        }
    }
</style>
